<template>
  <div
    :class="className"
    :ref="echartsId"
    :style="{height:height,width:width}"
  />
</template>

<script>
// import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '../mixins/resize'
import {echartsOptions} from './ExManyLineChartOptions.js'
import {getRandomID} from '@/utils'

export default {
  mixins: [resize],
  props: {
    pEchartsId: {
      type: String,
      // required:true,
      default: getRandomID()
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null,
      echartOptions: {}
    }
  },
  computed: {
    echartsId() {
      return 'echarts' + this.pEchartsId
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  created() {
    // 初始化图表的options   
    console.log('createdechartsOptionsJSON:', echartsOptions);
    this.echartOptions = echartsOptions
  },
  mounted() {
    /********重新渲染图表*********
     * this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它，然后等待 DOM 更新。
     * 它跟全局方法 Vue.nextTick 一样，不同的是回调的 this 自动绑定到调用它的实例上。
     * 假设我们更改了某个dom元素内部的文本，而这时候我们想直接打印出这个被改变后的文本是需要dom更新之后才会实现的，
     */
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {

    //   释放图表资源
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      // 使用ref动态获取DOM对象
      let chartsDom = this.$refs[`${this.echartsId}`];
      // // 初始化图表对象
      this.chart = this.$echarts.init(chartsDom)

      // // 渲染
      this.echartOptions && this.setOptions(this.chartData)
    },
    setOptions(obj) {
      console.log('RRRRRR', obj);
      // 重置数据
      this.setEchartsData(obj)
      // console.log('echartOptions:::::重置数据',this.echartOptions);
      // 渲染
      this.chart.setOption(this.echartOptions, true)
      // 每次绘制，自动调整画布大小  
      this.resize()

    },
    // 重置图标数据
    setEchartsData({
                     tooltipFormatter,
                     legendData,
                     xAxisData,
                     seriesData
                   } = {}) {

      this.echartOptions.tooltip.formatter = tooltipFormatter
      this.echartOptions.legend.data = legendData
      this.echartOptions.xAxis.data = xAxisData
      this.echartOptions.series = seriesData

      console.log('this.echartOptionsthis.echartOptionsthis.echartOptionsthis.echartOptionsthis.echartOptions', this.echartOptions);
    }
  }
}
</script>
